var express = require('express');
var router = express.Router();

require("../db/mongoose-user")
var User = require("../db/mongoose-user").User;

//连接字符串
var DB_CONN_STR = 'mongodb://localhost/notes';


router.post('/register', function (req, res, next) {
    var json =
        {
            "code": "1",
            "succeed": "succeed",
            "content": {
                "msg": "密码错误"
            }
        };
    var platform = req.param('platform');
    var user_name = req.param('user_name');
    var user_password = req.param('user_password');
    var phone = req.param('phone');
    var user_email = req.param('user_email');

    if (platform == null) {
        FailureJson(json, res, "没有传平台参数");
        return;
    } else if (null === user_name) {
        FailureJson(json, res, "用户名为空");
        return;
    } else if (null === user_password) {
        FailureJson(json, res, "密码为空");
        return;
    } else if (null === phone) {
        FailureJson(json, res, "手机为空");
        return;
    } else if (null === user_email) {
        FailureJson(json, res, "邮箱为空");
        return;
    }
    User.find({'user_name': user_name}, function (err, docs) {
        // docs 是查询的结果数组 });
        if (err) {
            console.log(err);
        } else if (docs.length>0) {
            FailureJson(json, res, "用户已经存在");
        }else {
            //可以注册
            var user = new User({
                user_name: user_name,
                user_password: user_password,
                phone: phone,
                user_email: user_email,
                date: Date.now()
            });
            user.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('存入成功');
                    SucceeJson(json, res, "存入成功");
                }
            });
        }

    });



});
var FailureJson = function (json, res, msg) {
    json.code = "0";
    json.succeed = "failure";
    json.content.msg = msg;
    res.send(json);
};
var SucceeJson = function (json, res, msg) {
    json.code = "1";
    json.succeed = "succeed";
    json.content.msg = msg;
    res.send(json);
};

module.exports = router;
